package com.dc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.ResponseResultVO;
import com.dc.entity.Region;
import com.dc.entity.ro.RegionRO;
import com.dc.mapper.RegionMapper;
import com.dc.service.RegionService;
import com.dc.util.SnowflakeIdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

import static com.dc.common.ResponseResultVO.checkParameterIsNotNull;

@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {

    @Resource
    private RegionMapper regionMapper;


    @Override
    public ResponseResultVO insertRegion(RegionRO ro) {
        Region region = new Region();
        BeanUtils.copyProperties(ro, region);
        region.setId(SnowflakeIdWorker.generateId());
        return ResponseResultVO.insertResult(regionMapper.insert(region));
    }

    @Override
    public ResponseResultVO updateRegion(RegionRO ro) {
        checkParameterIsNotNull(String.valueOf(ro.getId()), "id不能为空");
        Region region = new Region();
        BeanUtils.copyProperties(ro, region);
        return ResponseResultVO.updateResult(regionMapper.updateById(region));
    }

    @Override
    public ResponseResultVO deleteRegion(String ids) {
        checkParameterIsNotNull(ids, "id不能为空");
        List<String> idList = Arrays.asList(ids.split(","));
        return ResponseResultVO.deleteResult(regionMapper.deleteBatchIds(idList));
    }

    @Override
    public ResponseResultVO selectRegionList() {
        List<Region> regions = regionMapper.selectList(new QueryWrapper<Region>().lambda().eq(Region::getParentId, 0));
        for (Region vo : regions) {
            this.treeUp(vo);
        }
        return ResponseResultVO.successResult(regions);
    }

    /**
     * 递归向下查询
     */
    private void treeUp(Region vo) {
        List<Region> regions = regionMapper.selectList(new QueryWrapper<Region>().lambda().eq(Region::getParentId, vo.getId()));
        for (Region sss : regions) {
            vo.setChildren(regions);
            treeUp(sss);
        }
    }

    @Override
    public ResponseResultVO selectRegionFloorList() {
        return ResponseResultVO.successResult(regionMapper.selectList(new QueryWrapper<Region>().lambda()
                .eq(Region::getParentId, 0)));
    }
}
